"""
同步对称操作数据

将 bilbao_point_groups.json 中的 operations 数据
同步到 crystallographic_point_groups.json
"""

import json
from pathlib import Path


def sync_operations():
    """同步对称操作数据"""
    data_dir = Path(__file__).parent.parent / "data"

    # 读取源文件（bilbao_point_groups.json）
    char_tables_file = data_dir / "bilbao_point_groups.json"
    print(f"读取源文件: {char_tables_file.name}")

    with open(char_tables_file, "r", encoding="utf-8") as f:
        char_tables = json.load(f)

    # 创建 Schoenflies -> operations / generators 映射
    operations_map = {}
    generators_map = {}
    subgroups_map = {}
    for table in char_tables:
        schoenflies = table["schoenflies"]
        if "operations" in table:
            operations_map[schoenflies] = table["operations"]
        if "generators" in table:
            generators_map[schoenflies] = table["generators"]
        if "subgroups" in table:
            subgroups_map[schoenflies] = table["subgroups"]

    # 添加别名映射（不同命名但实际是同一个点群）
    # S6 = C3i (三方对称 + 反演中心)
    if "C3i" in operations_map and "S6" not in operations_map:
        operations_map["S6"] = operations_map["C3i"]
        generators_map["S6"] = generators_map.get("C3i", [])
        subgroups_map["S6"] = subgroups_map.get("C3i", [])

    print(f"  ✓ 找到 {len(operations_map)} 个点群的操作数据")

    # 读取目标文件（crystallographic_point_groups.json）
    cryst_file = data_dir / "crystallographic_point_groups.json"
    print(f"\n读取目标文件: {cryst_file.name}")

    with open(cryst_file, "r", encoding="utf-8") as f:
        cryst_groups = json.load(f)

    print(f"  ✓ 找到 {len(cryst_groups)} 个点群")

    # 同步数据
    print("\n同步操作数据...")
    updated_count = 0

    for group in cryst_groups:
        schoenflies = group["schoenflies"]

        if schoenflies in operations_map:
            # 替换 operations 数据
            group["operations"] = operations_map[schoenflies]
            group["generators"] = generators_map.get(schoenflies, group.get("generators", []))
            if schoenflies in subgroups_map:
                group["subgroups"] = subgroups_map[schoenflies]
            updated_count += 1

            # 验证 ITA 符号
            ita_filled = sum(1 for op in group["operations"] if op.get("ita_symbol", "").strip())
            total_ops = len(group["operations"])

            print(
                f"  ✓ {schoenflies:5s}: {total_ops} 操作, ITA: {ita_filled}/{total_ops}, "
                f"生成元 {len(group['generators'])}, 子群 {len(group.get('subgroups', []))}"
            )

    # 保存更新后的文件
    print(f"\n保存更新后的文件...")
    with open(cryst_file, "w", encoding="utf-8") as f:
        json.dump(cryst_groups, f, ensure_ascii=False, indent=2)

    print(f"  ✓ 已更新 {updated_count}/{len(cryst_groups)} 个点群")

    # 验证数据完整性
    print("\n" + "=" * 70)
    print("数据完整性验证")
    print("=" * 70)

    total_ops = sum(len(pg["operations"]) for pg in cryst_groups)
    ita_filled = sum(1 for pg in cryst_groups for op in pg["operations"] if op.get("ita_symbol", "").strip())
    seitz_filled = sum(1 for pg in cryst_groups for op in pg["operations"] if op.get("seitz", "").strip())

    print(f"总操作数: {total_ops}")
    print(f"ITA symbol: {ita_filled}/{total_ops} ({ita_filled*100//total_ops}%)")
    print(f"Seitz: {seitz_filled}/{total_ops} ({seitz_filled*100//total_ops}%)")

    # 列出仍然有空 ITA 的点群
    groups_with_empty_ita = []
    for pg in cryst_groups:
        empty_count = sum(1 for op in pg["operations"] if not op.get("ita_symbol", "").strip())
        if empty_count > 0:
            groups_with_empty_ita.append((pg["schoenflies"], empty_count, len(pg["operations"])))

    if groups_with_empty_ita:
        print(f"\n⚠️  {len(groups_with_empty_ita)} 个点群仍有空 ITA 符号:")
        for schoenflies, empty, total in groups_with_empty_ita:
            print(f"  - {schoenflies}: {empty}/{total} 空")
    else:
        print("\n✅ 所有点群的 ITA 符号都已填充！")


if __name__ == "__main__":
    sync_operations()
